package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class ServeSocketThread extends Thread {
	private ServerSocket s;

	public ServeSocketThread(ServerSocket s) {
		this.s = s;
	}

	@Override
	public void run() {

		try {
			// 1.创建一个ServeSocket对象，指定端口

			// 2.监听客户请求

			Socket socket = s.accept();
			// 3.打开输入流，处理客户请求

			InputStream is = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String info = null;
			// 服务器需要给客户端一个反应

			java.io.OutputStream os = socket.getOutputStream();
			while ((info = br.readLine()) != null) {
				String outfo;
				if (info.equals("时间")) {
					SimpleDateFormat sdf = new SimpleDateFormat();
					Calendar c = Calendar.getInstance();
					String time = sdf.format(c.getTime());
					outfo = time + "\r\n";
				} else {
					outfo = "输入不正确，无法获得时间\r\n";
				}
				os.write(outfo.getBytes());
				os.flush();
			}
			// 关闭资源

			br.close();
			is.close();
			os.close();
			socket.close();
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
